package com.course02.order_backend.service.Ost;

import com.course02.order_backend.dto.Ost.UserDTO;
import com.course02.order_backend.entity.Ost.User;
import com.course02.order_backend.exception.Ost.DuplicateException;
import com.course02.order_backend.mapper.Ost.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    private final UserMapper userMapper;
    private final BCryptPasswordEncoder passwordEncoder;
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    @Autowired
    public UserService(UserMapper userMapper, BCryptPasswordEncoder passwordEncoder) {
        this.userMapper = userMapper;
        this.passwordEncoder = passwordEncoder;
    }

    public int register(UserDTO userDTO) {
        // 1. 检查用户名是否已存在
        int usernameCount = userMapper.countByUsername(userDTO.getUsername());
        if (usernameCount > 0) {
            throw new DuplicateException("用户名已被注册");
        }

        // 2. 检查手机号是否已存在
        if (userDTO.getPhone() != null && !userDTO.getPhone().isEmpty()) {
            int phoneCount = userMapper.countByPhone(userDTO.getPhone());
            if (phoneCount > 0) {
                throw new DuplicateException("手机号已被注册");
            }
        }

        // 3. DTO转换为实体类（移除idCard相关代码）
        User user = new User();
        user.setUsername(userDTO.getUsername());
        user.setPassword(passwordEncoder.encode(userDTO.getPassword())); // 密码加密
        user.setRealName(userDTO.getRealName());
        user.setGender(userDTO.getGender());
        user.setPhone(userDTO.getPhone());
        user.setEmail(userDTO.getEmail());
        user.setIsEnabled(1); // 默认启用账号

        // 4. 插入数据库
        int rows = userMapper.insert(user);
        if (rows <= 0) {
            throw new RuntimeException("注册失败，数据库插入异常");
        }

        return rows;
    }
}